#pragma once

#include <iostream>
#include <memory>
#include "Epoller.hpp"
#include "Socket.hpp"
#include "Connection.hpp"
#include "Common.hpp"
#include "Channel.hpp"

using namespace SocketModule;

class Listener : public Connection
{
public:
    Listener(int port = defaultport)
        : _port(port),
          _listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildListenSocketMethod(_port);
        SetEvent(EPOLLIN | EPOLLET);
        SetNonBlock(_listensock->Fd());
    }

    void Recver()
    {
        // LOG(LogLevel::DEBUG) << "进入Listener模块函数...";
        InetAddr client;
        while (true)
        {
            int sockfd = _listensock->Accept(&client);
            if (sockfd == ACCEPT_ERR)
                break;
            else if (sockfd == ACCEPT_CONTINUE)
                continue;
            else if (sockfd == ACCEPT_DONE)
                break;
            else
            {
                std::shared_ptr<Connection> conn = std::make_shared<Channel>(sockfd, client);
                conn->SetEvent(EPOLLIN | EPOLLET);

                if (_handler != nullptr)
                {
                    conn->RegisterHandler(_handler);
                }

                GetOwner()->AddConnection(conn);
            }
        }
    }

    void Sender() {}

    void Excepter() {}

    int GetSockFd()
    {
        return _listensock->Fd();
    }

    ~Listener()
    {
    }

private:
    int _port;
    std::unique_ptr<Socket> _listensock;
};